<template>
  <div>
    <van-nav-bar :title="t('check.inventoryStart')" left-arrow @click-left="onClickLeft" placeholder fixed />

    <van-cell-group style="background: none">
     <van-form @submit="onSubmit">
        <van-form style="margin-bottom: 1vh">
          <van-cell :title="t('check.inventoryNo')" :value="orderForm ? orderForm.inventoryNo : null"></van-cell>
          <van-cell :title="t('抓码比对.库位')" :value="goodsForm ? goodsForm.locationCode : null"></van-cell>
          <van-cell :title="t('抓码比对.SKU')" :value="goodsForm ? goodsForm.skuCode : null"></van-cell>
          <van-cell :title="t('check.customCode')" :value="goodsForm ? goodsForm.customerCode : null"></van-cell>
        </van-form>

        <scanning ref="containerCodeRef" @keydownEnter="handleScanContainerCode" :placeholder="t('抓码比对.请扫描流转箱号')"
          style="height: 50px; display: none"></scanning>
        <scanning ref="skuCodeRef" @keydownEnter="handleScanSkuCode" :placeholder="t('抓码比对.请扫描SKU')"
          :isFocus="true" style="height: 50px;"></scanning>
        <van-cell class="exp">
          <template #title>
            <span class="van-multi-ellipsis--l1">{{ t('check.inventoryQty') }}</span>
          </template>
          <template #value>
            <span class="font-size1 van-color-text-assist">
              {{ goodsForm.scanNum }}
            </span>
          </template>
        </van-cell>

        <van-popup v-model:show="showBottom" position="bottom" :style="{ height: '30%' }">
          <van-button type="success" size="small" style="width: 4rem" @click="orderUploadSubmit">{{ t('抓码比对.上传')
          }}</van-button>
          <van-field>
            <template #input>
              <van-col span="3" style="text-align: center">
                <van-checkbox v-model="allCheckbox" @click="selectionAll"></van-checkbox>
              </van-col>
              <van-col span="7" style="text-align: center">
                {{ t('sku') }}
              </van-col>
              <van-col span="7" style="text-align: center">
                {{ t('check.stockQty') }}
              </van-col>
              <van-col span="7" style="text-align: center">
                {{ t('check.inventoryQty') }}
              </van-col>
            </template>
          </van-field>
          <div style="height: 68%; overflow: auto">
            <van-checkbox-group v-model="selection">
              <van-field v-for="(item, index) in orderFormList" :key="index">
                <template #input>
                  <van-col span="3" style="text-align: center">
                    <van-checkbox :name="item"></van-checkbox>
                  </van-col>
                  <van-col span="7" style="text-align: center">
                    {{ item.skuCode }}
                  </van-col>
                  <van-col span="7" style="text-align: center">
                    {{ item.sysInventoryQty }}
                  </van-col>
                  <van-col span="7" style="text-align: center">
                    {{ item.scanNum }}
                  </van-col>
                </template>
              </van-field>
            </van-checkbox-group>
          </div>
        </van-popup>
      </van-form>
    </van-cell-group>
    <div style="display: flex; width: 100%; justify-content: space-around; margin-top: 10px;">
      <van-icon @click="onLeft" name="arrow-left" size="30px"
        style="background-color: #00b7ff; padding: 5px; border-radius: 20px;" color="white" />
      <van-icon @click="onRight" name="arrow" size="30px"
        style="background-color: #00b7ff; padding: 5px; border-radius: 20px;" color="white" />
    </div>
    <div style="position: absolute; bottom: 0; display: flex; width: 100%;">
      <van-button block type="primary" @click="orderSubmit" style="height: 9vh">{{ t('抓码比对.确认') }}</van-button>
      <van-button block type="warning" @click="orderUpload" style="height: 9vh">{{ t('抓码比对.等待上传') }}（{{
        orderFormList?.length
      }}）</van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useI18n } from "vue-i18n";
import Scanning from "@/views/components/Scanning/index.vue";
import { postRequest, scanSuccess, scanFail } from "@/api";
import { AppToast } from "@/utils/appToast";
import { useRoute } from "vue-router";
import { Ref } from "vue";

const route = useRoute();
const query = route.query;

const containerCodeRef = ref(null)
const skuCodeRef = ref(null)
const allCheckbox = ref(false)
const showBottom = ref(false)
const selection = ref([])
let index = 0
const { t } = useI18n();
const onClickLeft = () => history.back();

const resetForm = () => {
  // form.value = {
  //   orderNo: undefined,
  //   trackingNo: undefined,
  //   customerCode: undefined,
  //   deliveredBoxNum: undefined,
  //   undeliveredBoxNum: undefined,
  //   inventoryNo: undefined,
  // }
};

interface OrderForm {
  goodsSkuCode: string,
  goodsQuantity: number,
  locationCode: string,
  containerCode: string,
  status: string,
  inventoryNo: string,
  scanNum: number,
};

interface OrderGoodsForm {
  locationCode: string,
  locationPickSort: number,
  containerCode: string,
  skuCode: string,
  goodsNum: number,
  pack: string,
  scanNum: number,
  status: boolean,
  skuId: number,
  inventoryQty: number,
  remark: string,
  customerCode: number,
  sysInventoryQty: number,
}

let orderFormList = ref<OrderGoodsForm[]>();
const orderForm: Ref<OrderForm> = ref(null)
const goodsForm: Ref<OrderGoodsForm> = ref({
  locationCode: undefined,
  locationPickSort: undefined,
  containerCode: undefined,
  skuCode: undefined,
  goodsNum: undefined,
  pack: undefined,
  scanNum: undefined,
  status: undefined,
  skuId: undefined,
  inventoryQty: undefined,
  remark: undefined,
  customerCode: undefined,
  sysInventoryQty: undefined,
})


resetForm();
const handleScanContainerCode = value => {
  if (goodsForm.value.containerCode !== value) {
    scanFail()
    AppToast(t("抓码比对.流转箱号不正确"), "fail")
    containerCodeRef.value.setValue(undefined)
    return
  }
  scanSuccess()
  AppToast(t("抓码比对.流转箱号扫描成功"), "success")
  skuCodeRef.value.setFocus()
}
const handleScanSkuCode = async value => {
  if (goodsForm.value.skuCode !== value) {
    scanFail()
    AppToast(t("抓码比对.SKU不正确"), "fail")
    skuCodeRef.value.setValue(undefined)
    return
  }
  if (goodsForm.value.scanNum === goodsForm.value.inventoryQty) {
    scanFail()
    AppToast(t("抓码比对.SKU已足够"), "fail")
    skuCodeRef.value.setValue(undefined)
    return
  }
  scanSuccess()
  AppToast(t("抓码比对.SKU扫描成功"), "success")
  skuCodeRef.value.setValue(undefined)
  goodsForm.value.scanNum++;
}

const selectionAll = () => {
  if (allCheckbox.value) {
    selection.value = orderFormList.value;
  } else {
    selection.value = []
  }
}

const onSubmit = () => {
  // TODO
}
const orderSubmit = () => {
  onRight()
}

const orderUpload = () => {
  showBottom.value = true
}

const onLeft = () => {
  index--;
  if (index < 0) {
    AppToast(t("已经是第一个了"), "success");
    index++;
    return;
  }
  // containerCodeRef.value.setValue(undefined)
  // skuCodeRef.value.setValue(undefined)
  // containerCodeRef.value.setFocus()
  skuCodeRef.value.setValue(undefined);
  skuCodeRef.value.setFocus();
  goodsForm.value = orderFormList.value[index];
  containerCodeRef.value.setValue(goodsForm.value.containerCode);
}
const onRight = () => {
  index++;
  if (index >= orderFormList.value.length) {
    AppToast(t("已经是最后一个了"), "success");
    index--;
    return;
  }
  // containerCodeRef.value.setValue(undefined)
  // skuCodeRef.value.setValue(undefined)
  // containerCodeRef.value.setFocus()
  skuCodeRef.value.setValue(undefined);
  skuCodeRef.value.setFocus();
  goodsForm.value = orderFormList.value[index];
  containerCodeRef.value.setValue(goodsForm.value.containerCode);
}

const orderUploadSubmit = () => {
  if (orderFormList.value?.length === 0) {
    AppToast(t("抓码比对.选中订单不存在"), "fail")
    return
  }

  let details = selection.value?.map(item => {
    return {
      inventoryOrderDetailId: item.inventoryOrderDetailId,
      inventoryQty: item.scanNum
    }
  })

  postRequest("/inventoryOrder/uploadResult", {
    inventoryOrderId: Number(query.inventoryOrderId),
    details
  }).then(() => {
    AppToast(t("抓码比对.上传成功"), "success")
    resetForm()

    showBottom.value = false
    // goodsForm.value.scanNum = undefined
    // containerCodeRef.value.setValue(undefined)
    // skuCodeRef.value.setValue(undefined)
  })
}

onMounted(async () => {
  const res = await postRequest(
    '/inventoryOrder/get', {
      inventoryOrderId: query?.inventoryOrderId
  }
  )
  orderForm.value = res.data;
  orderFormList.value = res.data?.detail?.map(item => {
    item.scanNum = 0;
    return item;
  }) || []
  goodsForm.value = orderFormList.value[index];
  console.log(goodsForm.value);
  containerCodeRef.value.setValue(goodsForm.value.containerCode)
});
</script>

<style scoped lang="less">
:deep(.van-cell) {
  font-size: 1rem;
}

:deep(.van-nav-bar__title) {
  font-size: 1rem;
  font-weight: 500;
  color: white;
}

:deep(.van-nav-bar__content) {
  background: #1b82d2;
}

:deep(.van-nav-bar .van-icon) {
  color: white;
}

:deep(.van-button) {
  font-size: 1rem;
}

:deep(.van-field--disabled .van-field__label) {
  color: black;
}

:deep(.van-uploader__upload) {
  width: 120px;
  height: 120px;
}
</style>
